package com.hk.webapp.advice;

import com.hk.webapp.error.BusinessErrorEnum;
import com.hk.webapp.error.BusinessException;
import com.hk.webapp.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.PropertyAccessException;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.web.HttpMediaTypeException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * (C) Copyright 2017-2019
 * All rights reserved.
 * <p>
 * 全局异常处理
 *
 * @author DreamerCK
 * @date 2019-1-18 16:47
 **/
@Slf4j
@RestControllerAdvice
public class GlobalHandlerExceptionAdvice {


    @ExceptionHandler(Exception.class)
    public ResultVo handlerInteriorException(Exception e, HttpServletRequest request) {
        log.error("you have an error:{}",e);
        if (e instanceof BusinessException) {
            BusinessException exception = (BusinessException) e;
            return ResultVo.createByError(exception.getMessage());
        } else if (e instanceof HttpMediaTypeException) {
            return ResultVo.createByErrorEnum(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR);
        } else if (e instanceof HttpMessageConversionException) {
            return ResultVo.createByErrorEnum(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR);
        } else if (e instanceof ServletRequestBindingException) {
            return ResultVo.createByErrorEnum(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR);
        } else if (e instanceof PropertyAccessException) {
            return ResultVo.createByErrorEnum(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            return ResultVo.createByErrorEnum(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR);
        }
        return ResultVo.createByErrorEnum(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR);
    }

}
